package com.mall.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.util.JsonResult;
import com.mall.user.common.exception.BusinessException;
import com.mall.user.common.response.ResultCode;
import com.mall.user.constant.UserConstant;
import com.mall.user.model.dto.favorite.UserFavoriteAddRequest;
import com.mall.user.model.entity.User;
import com.mall.user.model.vo.UserFavoriteVO;
import com.mall.user.service.UserFavoriteService;
import com.mall.user.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/favorite")
public class FavoriteController {

    @Resource
    private UserService userService;

    @Resource
    private UserFavoriteService userFavoriteService;

    /**
     * 检查用户是否有权限操作收藏（本人或管理员）
     */
    private void checkFavoritePermission(User currentUser, Long targetUserId) {
        if (currentUser == null) {
            throw new BusinessException(ResultCode.UNAUTHORIZED, "用户未登录");
        }
        
        // 如果是管理员，允许操作任何用户的收藏
        if (UserConstant.ADMIN_ROLE.equals(currentUser.getUser_type())) {
            return;
        }
        
        // 如果不是管理员，只能操作自己的收藏
        if (!currentUser.getId().equals(targetUserId)) {
            throw new BusinessException(ResultCode.FORBIDDEN, "无权限操作他人收藏");
        }
    }

    /**
     * 添加收藏
     */
    @PostMapping("/add")
    public JsonResult<Long> addFavorite(@Valid @RequestBody UserFavoriteAddRequest userFavoriteAddRequest, HttpServletRequest request) {
        if (userFavoriteAddRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR);
        }
        Long productId = userFavoriteAddRequest.getProductId();
        if (productId == null || productId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "商品ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkFavoritePermission(loginUser, loginUser.getId());
        
        Long favoriteId = userFavoriteService.addFavorite(loginUser.getId(), productId);
        return JsonResult.success(favoriteId);
    }

    /**
     * 取消收藏
     */
    @PostMapping("/delete")
    public JsonResult<Boolean> removeFavorite(@Valid @RequestBody UserFavoriteAddRequest userFavoriteAddRequest, HttpServletRequest request) {
        if (userFavoriteAddRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR);
        }
        Long productId = userFavoriteAddRequest.getProductId();
        if (productId == null || productId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "商品ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkFavoritePermission(loginUser, loginUser.getId());
        
        boolean result = userFavoriteService.removeFavorite(loginUser.getId(), productId);
        return JsonResult.success(result);
    }

    /**
     * 检查是否已收藏
     */
    @GetMapping("/check/{productId}")
    public JsonResult<Boolean> checkFavorite(@PathVariable Long productId, HttpServletRequest request) {
        if (productId == null || productId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "商品ID不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkFavoritePermission(loginUser, loginUser.getId());
        
        boolean isFavorite = userFavoriteService.isFavorite(loginUser.getId(), productId);
        return JsonResult.success(isFavorite);
    }

    /**
     * 获取用户收藏列表
     */
    @GetMapping("/list")
    public JsonResult<Page<UserFavoriteVO>> getUserFavorites(
            @RequestParam(defaultValue = "1") int current,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        
        User loginUser = userService.getLoginUser(request);
        // 只有本人或管理员才能操作
        checkFavoritePermission(loginUser, loginUser.getId());
        
        Page<UserFavoriteVO> favoritePage = userFavoriteService.getUserFavorites(loginUser.getId(), current, pageSize);
        return JsonResult.success(favoritePage);
    }
}
